local debugstack
do -- global.lua
	local getinfo = debug.getinfo
	local max = math.max
	local concat = table.concat

	local function filtersource(src)
		if not src then return "[?]" end
		if config and config.ADDON_PATH and config.ADDON_PATH ~= "" then
			src = src:replace(config.ADDON_PATH, "wow/Interface/AddOns")
		end
		src = src:replace("/", "\\") -- we hide the fact that we're on linux
		src = src:replace("..\\", "wow\\Interface\\AddOns\\") -- let's add a "real" addon path, so that AceDB initialize.
		if src:sub(1, 1) == "@" then
			src = src:sub(2)
		end
		return src
	end

	local function formatinfo(info)
		if not info then return "**error**" end
		local source = filtersource(info.source)
		if info.currentline then
			source = source..":"..info.currentline
		end
		return ("\t%s in (%s) %s (%s) <%d-%d>"):format(source, info.namewhat, info.name or "?", info.what, info.linedefined, info.lastlinedefined)
	end

	debugstack = function (start, top, bottom)
		if not bottom then bottom = 10 end
		if not top then top = 12 end
		start = (start or 1) + 1

		local count = max(2, start)
		while getinfo(count) do
			count = count + 1
		end

		count = count - start

		if top + bottom >= count then
			top = count
			bottom = nil
		end

		local s = {"stack traceback:"}
		for i = 1, top, 1 do
			s[#s + 1] = formatinfo(getinfo(start + i - 1))
		end
		if bottom then
			s[#s + 1] = "\t..."
			for i = bottom , 1, -1 do
				s[#s + 1] = formatinfo(getinfo(count - i + 1))
			end
		end

		return concat(s, "\n")
	end
end

local function debuglocals (level)
	local t = {}
	local index = 1
	while true do
		local name, value = debug.getlocal(level + 1, index)
		if not name then break end
		t[index] = string.format("%s = %s", name, tostring(value))
		index = index + 1
	end
	return table.concat(t, "\n")
end

if TEST then
	local function f (level)
		if level <= 0 then
			local s = debugstack()
			return s
		else
			local s = f(level - 1)
			return s
		end
	end

	local t = function ()
		local s = {}
		for k, v in pairs(debug.getinfo(1)) do
			s[#s + 1] = ("%s = %s"):format(tostring(k), tostring(v))
		end
		return table.concat(s, "\n")
	end

	print(t())
	print(f(150))
elseif api.global then
	api.global.debugstack = debugstack
	api.global.debuglocals = debuglocals
end
